#!/usr/bin/env python

import sqlite3
import logging
import sys

class ChatUser():

    conn = None
    userList = None
    cursor = None

    def __init__(self, jid='', nick='', available=False, ban=False, inviting=False, inviteby=''):
        self.jid = jid
        self.nick = nick
        self.available = available
        self.ban = ban
        self.inviting = inviting
        self.inviteby = inviteby

    @classmethod
    def getByNick(cls, nick):
        cls.open()
        for u in cls.userList:
            if (u.nick == nick):
                return u

    @classmethod
    def getByJid(cls, jid):
        cls.open()
        for u in cls.userList:
            if (u.jid == jid):
                return u

    @classmethod
    def all(cls):
        cls.open()
        return cls.userList

    @classmethod
    def open(cls):
        if (not cls.conn):
            cls.conn = sqlite3.connect('gootalk.db')
            cls.cursor = cls.conn.cursor()
        if (not cls.userList):
            cls.cursor.execute('SELECT * FROM user')
            cls.userList = []
            for u in cls.cursor.fetchall():
                cls.userList.append(
                        ChatUser(
                                jid = u[0],
                                nick = u[1],
                                available = u[2],
                                ban = u[3],
                                inviting = u[4],
                                inviteby = u[5]
                            )
                        )

    @classmethod
    def close(cls):
        if (cls.conn):
            cls.conn.close()
        cls.userList = None

    @classmethod
    def init(cls):
        if (not cls.conn):
            cls.conn = sqlite3.connect('gootalk.db')
            cls.cursor = cls.conn.cursor()
        logging.info('Init DB')
        cls.cursor.execute('CREATE TABLE user (jid NVARCHAR(128) PRIMARY KEY, nick NVARCHAR(128) UNIQUE, available BOOLEAN, ban BOOLEAN, inviting BOOLEAN, inviteby NVARCHAR(128));')
        cls.conn.commit()
        cls.userList = []

    @classmethod
    def sql(cls, sql):
        cls.open()
        cls.cursor.execute(sql)
        cls.conn.commit()

    def put(self):
        ChatUser.open()
        sql = ''
        if (self not in ChatUser.userList):
            ChatUser.userList.append(self)
            sql = 'INSERT INTO user VALUES(\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\')' % (self.jid, self.nick, self.available, self.ban, self.inviting, self.inviteby)
        else:
            sql = 'UPDATE user SET nick=\'%s\', available=\'%s\', ban=\'%s\', inviting=\'%s\', inviteby=\'%s\' WHERE jid=\'%s\'' % (self.nick, self.available, self.ban, self.inviting, self.inviteby, self.jid)
        logging.info(sql)
        ChatUser.cursor.execute(sql)
        ChatUser.conn.commit()


if __name__ == '__main__':
	ChatUser.sql(sys.argv[1])
